const state = {
  config: null,
  socket: null,
  messages: [],
  isConnected: false,
  reconnectError: false,
  currentUrl: null, // 新增字段用于记录当前的 ws_url
  heartbeatInterval: null, // 心跳定时器
  heartbeatTimeout: null, // 心跳超时定时器
  heartbeatIntervalTime: 30000, // 心跳间隔时间（30秒）
  heartbeatTimeoutTime: 60000, // 心跳超时时间（60秒）
};
const mutations = {
  SET_CONFIG(state, config) {
    state.config = config;
  },
  SET_SOCKET(state, socket) {
    state.socket = socket;
  },
  ADD_MESSAGE(state, message) {
    state.messages.push(message);
    // 数组最多保留100条记录
    // if (state.messages.length > 100) {
    //   state.messages.shift();
    // }
  },
  SET_CONNECTED(state, isConnected) {
    state.isConnected = isConnected;
  },
  SET_RECONNECT_ERROR(state, reconnectError) {
    state.reconnectError = reconnectError;
  },
  SET_CURRENT_URL(state, url) {
    // 新增 mutation 用于设置当前的 ws_url
    state.currentUrl = url;
  },
  SET_HEARTBEAT_INTERVAL(state, interval) {
    state.heartbeatInterval = interval;
  },
  SET_HEARTBEAT_TIMEOUT(state, timeout) {
    state.heartbeatTimeout = timeout;
  },
};
const actions = {
  connect({ commit, dispatch }, ws_url) {
    if (state.currentUrl === ws_url) {
      console.log('Already connected to this URL:', ws_url);
      return;
    }
    if (state.socket) {
      state.socket.close();
    }
    const socket = new WebSocket(`${ws_url}`);

    socket.onopen = () => {
      console.log('已连接到 WebSocket 服务器');
      commit('SET_CONNECTED', true);
      commit('SET_RECONNECT_ERROR', false);
      commit('SET_CURRENT_URL', ws_url); // 设置当前的 ws_url
      // dispatch('startHeartbeat');
    };

    socket.onmessage = (event) => {
      console.log('WebSocket 服务器:', event.data);
      const data = JSON.parse(event.data);
      if (data.type === 'heartbeat_response') {
        dispatch('handleHeartbeatResponse');
      } else {
        commit('ADD_MESSAGE', event.data);
      }
    };

    socket.onclose = () => {
      console.log('已断开与 WebSocket 服务器的连接');
      commit('SET_CONNECTED', false);
      commit('SET_RECONNECT_ERROR', true);
      commit('SET_CURRENT_URL', null); // 清除当前的 ws_url
      // 尝试重新连接
      setTimeout(() => {
        this.dispatch('connect');
      }, 5000);
    };

    socket.onerror = (error) => {
      console.error('WebSocket 错误:', error);
      commit('SET_RECONNECT_ERROR', true);
      // dispatch('stopHeartbeat');
    };

    commit('SET_SOCKET', socket);
  },
  close({ commit }) {
    if (state.socket) {
      state.socket.close();
      commit('SET_SOCKET', null);
      commit('SET_CONNECTED', false);
      commit('SET_RECONNECT_ERROR', false);
      commit('SET_CURRENT_URL', null); // 清除当前的 ws_url
      // dispatch('stopHeartbeat');
    }
  },
  sendMessage({ state }, message) {
    if (state.socket && state.isConnected) {
      try {
        // 将对象转换为 JSON 字符串
        const messageString = JSON.stringify(message);
        state.socket.send(messageString);
      } catch (error) {
        // 不是对象直接发送字符串
        console.error('发送消息时发生错误:', error);
        state.socket.send(message);
      }
    } else {
      console.error('WebSocket 未连接');
    }
  },
  startHeartbeat({ commit, dispatch, state }) {
    if (state.heartbeatInterval) {
      clearInterval(state.heartbeatInterval);
    }
    if (state.heartbeatTimeout) {
      clearTimeout(state.heartbeatTimeout);
    }

    const interval = setInterval(() => {
      dispatch('sendHeartbeat');
    }, state.heartbeatIntervalTime);

    const timeout = setTimeout(() => {
      console.log('心跳超时，断开连接并尝试重新连接');
      if (state.socket) {
        state.socket.close();
      }
    }, state.heartbeatTimeoutTime);

    commit('SET_HEARTBEAT_INTERVAL', interval);
    commit('SET_HEARTBEAT_TIMEOUT', timeout);
  },
  stopHeartbeat({ commit, state }) {
    if (state.heartbeatInterval) {
      clearInterval(state.heartbeatInterval);
      commit('SET_HEARTBEAT_INTERVAL', null);
    }
    if (state.heartbeatTimeout) {
      clearTimeout(state.heartbeatTimeout);
      commit('SET_HEARTBEAT_TIMEOUT', null);
    }
  },
  sendHeartbeat({ state }) {
    if (state.socket && state.isConnected) {
      const heartbeatMessage = JSON.stringify({ type: 'heartbeat' });
      state.socket.send(heartbeatMessage);
      console.log('Heartbeat sent');
    } else {
      console.warn('WebSocket is not open, stopping heartbeat');
      this.dispatch('stopHeartbeat');
    }
  },
  handleHeartbeatResponse({ dispatch, commit, state }) {
    if (state.heartbeatTimeout) {
      clearTimeout(state.heartbeatTimeout);
    }

    const timeout = setTimeout(() => {
      console.log('心跳超时，断开连接并尝试重新连接');
      if (state.socket) {
        state.socket.close();
      }
    }, state.heartbeatTimeoutTime);

    dispatch('stopHeartbeat');
    dispatch('startHeartbeat');
    commit('SET_HEARTBEAT_TIMEOUT', timeout);
  },
};
const getters = {
  socket: (state) => state.socket,
  config: (state) => state.config,
  messages: (state) => state.messages,
  isConnected: (state) => state.isConnected,
  reconnectError: (state) => state.reconnectError,
  currentUrl: (state) => state.currentUrl,
};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
};
